<template>
  <div class="zzx">
  <div class="message-center">
    <div class="message-header">
      <h2>消息中心</h2>
      <div class="message-tabs">
        <el-radio-group v-model="activeTab" @change="handleTabChange">
          <el-radio-button label="received">收到的消息</el-radio-button>
          <el-radio-button label="sent">发送的消息</el-radio-button>
        </el-radio-group>
      </div>
    </div>

    <!-- 消息列表 -->
    <div class="message-list" v-loading="loading">
      <div v-if="messages.length > 0">
        <div v-for="msg in messages" :key="msg.id" class="message-item" :class="{'unread': !msg.isRead && activeTab === 'received'}">
          <div class="message-content">
            <p>{{msg.content}}</p>
            <div class="message-info">
              <span>{{formatTime(msg.createTime)}}</span>
              <template v-if="activeTab === 'received'">
                <span>来自: {{msg.fromUserName}}</span>
                <el-button type="text" @click="markAsRead(msg.id)" v-if="!msg.isRead">标记已读</el-button>
              </template>
              <template v-else>
                <span>发送给: {{msg.toUserName}}</span>
              </template>
              <el-button type="text" class="delete-btn" @click="deleteMessage(msg.id)">删除</el-button>
            </div>
          </div>
        </div>
      </div>
      <div v-else class="empty-tip">
        暂无消息
      </div>
    </div>

    <!-- 发送消息按钮 -->
    <el-button type="primary" class="send-btn" @click="showSendDialog">
      发送消息
    </el-button>

    <!-- 发送消息对话框 -->
    <el-dialog title="发送消息" :visible.sync="sendDialogVisible" width="500px">
      <el-form :model="messageForm" ref="messageForm" :rules="rules">
        <el-form-item label="接收者" prop="toUserId">
          <el-select
            v-model="messageForm.toUserId"
            filterable
            placeholder="请选择接收者">
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.username"
              :value="user.id">
              <span>{{ user.username }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="消息内容" prop="content">
          <el-input
            type="textarea"
            :rows="4"
            placeholder="请输入消息内容"
            v-model="messageForm.content">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="sendDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sendMessage">发 送</el-button>
      </div>
    </el-dialog>
  </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { formatDate } from '../utils'
import {
  getAllConsumer,
  sendMessage,
  getReceivedMessages,
  getSentMessages,
  markMessageAsRead,
  deleteMessage
} from '../api'

export default {
  name: 'Message',
  data() {
    return {
      activeTab: 'received',
      messages: [],
      loading: false,
      sendDialogVisible: false,
      messageForm: {
        toUserId: '',
        content: ''
      },
      userList: [],
      rules: {
        toUserId: [{ required: true, message: '请选择接收者', trigger: 'change' }],
        content: [{ required: true, message: '请输入消息内容', trigger: 'blur' }]
      }
    }
  },
  computed: {
    ...mapGetters(['userId'])
  },
  created() {
    console.log('当前用户ID:', this.userId)
    this.getMessages()
    this.getUserList()
  },
  watch: {
    userList: {
      handler(newVal) {
        console.log('用户列表更新:', newVal)
      },
      deep: true
    }
  },
  methods: {
    async getMessages() {
      this.loading = true
      try {
        const api = this.activeTab === 'received' ? getReceivedMessages : getSentMessages
        const res = await api(this.userId)
        if (res.code === 1) {
          this.messages = res.data
        }
      } finally {
        this.loading = false
      }
    },
    async getUserList() {
      try {
        const res = await getAllConsumer()
        if (res.code === 1) {
          console.log('用户列表:', res.data)
          this.userList = res.data
            .filter(user => user.id !== this.userId)
            .map(user => ({
              id: user.id,
              username: user.username || '未知用户'
            }))
          console.log('处理后的用户列表:', this.userList)
        } else {
          this.$message.error('获取用户列表失败')
        }
      } catch (error) {
        console.error('获取用户列表错误:', error)
        this.$message.error('获取用户列表失败')
      }
    },
    handleTabChange() {
      this.getMessages()
    },
    async markAsRead(messageId) {
      const res = await markMessageAsRead(messageId)
      if (res.code === 1) {
        this.$message.success('已标记为已读')
        this.getMessages()
        this.$root.$emit('updateUnreadCount')
      }
    },
    async deleteMessage(messageId) {
      try {
        await this.$confirm('确定删除该消息?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        const res = await deleteMessage(messageId)
        if (res.code === 1) {
          this.$message.success('删除成功')
          this.getMessages()
        }
      } catch (e) {
        // 取消删除
      }
    },
    showSendDialog() {
      this.messageForm = {
        toUserId: '',
        content: ''
      }
      this.sendDialogVisible = true
    },
    async sendMessage() {
      try {
        await this.$refs.messageForm.validate()
        const params = {
          fromUserId: this.userId,
          toUserId: this.messageForm.toUserId,
          content: this.messageForm.content,
          type: 0
        }
        console.log('发送消息参数:', params)
        const res = await sendMessage(params)
        console.log('发送消息响应:', res)

        if (res.code === 1) {
          this.$message.success('发送成功')
          this.sendDialogVisible = false
          if (this.activeTab === 'sent') {
            this.getMessages()
          }
        } else {
          this.$message.error(res.msg || '发送失败')
        }
      } catch (error) {
        console.error('发送消息错误:', error)
        this.$message.error('发送失败：' + (error.message || '未知错误'))
      }
    },
    formatTime(time) {
      return formatDate(new Date(time), 'yyyy-MM-dd hh:mm')
    }
  }
}
</script>

<style scoped>
.zzx{
  background-color: white;
}
.message-center {
  padding: 20px;
  padding-bottom: 120px;
  min-height: calc(100vh - 70px - 120px);
}
.send-btn{
  background-color: #ef7089;
}
el-radio-group{
  background-color: #ef7089;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}


.message-item {
  padding: 15px;
  background-color: snow;
  border-bottom: 1px solid #eee;
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2); /* 更大的模糊半径和更深的颜色 */
}


.message-item.unread {
  background-color: #f5f7fa;
}

.message-content {
  margin-bottom: 10px;
}

.message-info {
  font-size: 12px;
  color: #999;
  display: flex;
  align-items: center;
}

.message-info > * {
  margin-right: 15px;
}

.delete-btn {
  color: #f56c6c;
}

.empty-tip {
  text-align: center;
  color: #909399;
  margin-top: 100px;
}

.send-btn {
  position: fixed;
  right: 40px;
  bottom: 120px;
  z-index: 100;
}
</style>
